import {addToCart, reqBatchCheckCart, reqCartList, reqCheckCart, reqDeleteCart,reqBatchDeleteCart} from "@/api";

const state = {
    cartList: []
}
const mutations = {
    RECRIVE_CARTLIST(state, carList) {
        state.cartList = carList
    }
}
const actions = {
    async addShopCart({commit}, {skuId, skuNum}) {
        const result = await addToCart(skuId, skuNum)
        if (result && result.code === 200) {
            console.log("添加成功")
            return 'ok'
        } else {
            return Promise.reject('添加购物车失败');
        }
    },
    async getCartList({commit}) {
        try {
            let result = await reqCartList();
            if (result && result.code === 200) {
                commit('RECRIVE_CARTLIST', result.data);
            }
        } catch (err) {
            console.log("请求购物车数据失败")
        }
    },
    async setCheckCart({commit}, {skuId, isChecked}) {
        const result = await reqCheckCart(skuId, isChecked);
        if (result && result.code === 200) {
            return "成功"
        } else {
            return Promise.reject("请求修改状态失败")
        }
    },
    async setDeleteCart({commit}, skuId) {
        const result = await reqDeleteCart(skuId);
        if (result && result.code === 200) {
            return "删除成功"
        } else {
            return Promise.reject('删除失败');
        }
    },
    //修改是否全部选中
    async setBatchCheckCart({commit}, {isChecked, skuIdList}) {
        const result = await reqBatchCheckCart(isChecked, skuIdList);
        if (result && result.code === 200) {
            return "成功"
        } else {
            return Promise.reject(new Error('全部选中修改失败'));
        }
    },
    // 批量删除
    async setBatchDeleteCart({ commit }, skuIdList) {
        let result = await reqBatchDeleteCart(skuIdList);
        if (result && result.code === 200) {
            return 'ok'
        }
        return Promise.reject(new Error('批量删除商品失败'))
    },
}
const getters = {}

export default {
    namespaced: true,
    state,
    mutations,
    actions,
    getters
}